package net.sxnic.ugr.user.action;

import java.util.ArrayList;
import java.util.List;

import net.sxnic.ugr.UgrActionSupport;
import net.sxnic.ugr.context.AppContext;
import net.sxnic.ugr.group.Group;
import net.sxnic.ugr.group.GroupManager;
import net.sxnic.ugr.role.Role;
import net.sxnic.ugr.security.AuthorizationManager;
import net.sxnic.ugr.user.User;
import net.sxnic.ugr.user.UserManager;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 
 * Introduction：用户删除action类
 * 
 * @author 孙宇飞 create date : 2010-5-16
 * @author 吕盛槐 update date : 2011-9-26
 */
@SuppressWarnings("serial")
public class Delete extends UgrActionSupport {

	private static final Log log = LogFactory.getLog(Delete.class);

	@Autowired
	private UserManager userManager;

	@Autowired
	private GroupManager groupManager;

	public String execute() throws Exception {

		try {
			checkRoles(Role.SYSTEM_ADMIN);

			// 存放在状态信息中显示的用户名
			List<String> userNames = new ArrayList<String>();

			User toDelete = userManager.get(id);

			// 如果是考核组用户，设定为无效
			if (toDelete.getUsername().contains("khz")) {
				toDelete.setEnabled(false);
				userManager.update(toDelete);

				// 保存删除成功的信息
				msg = "deleteSuccess";
				return SUCCESS;
			}

			if (toDelete == null) {
				return INPUT;
			}

			// 用户管理员不可以删除系统管理员
			// 只有系统管理员才可以删除系统管理员
			if (authorizationManager.isUserGroupInRole(toDelete,
					Role.SYSTEM_ADMIN)
					&& !authorizationManager.isInRole(
							AuthorizationManager.IF_ALL_GRANTED,
							Role.SYSTEM_ADMIN)) {

				log.warn("尝试删除系统管理员 " + toDelete.getUsername() + ", 这可能是个攻击行为.");
				notAuthorized();
			}

			// 不可以删除自己
			if (toDelete != null
					&& !userManager.findBy("username",
							AppContext.getUserName(request)).equals(toDelete)) {

				// 从组中移除
				List<Group> groups = new ArrayList<Group>();
				groups.addAll(toDelete.getGroups());

				for (int i = 0; i < groups.size(); i++) {
					toDelete.getGroups().remove(groups.get(i));
				}

				// 去掉所有角色
				List<Role> roles = new ArrayList<Role>();
				roles.addAll(toDelete.getRoles());

				for (int i = 0; i < roles.size(); i++) {
					authorizationManager.revokeRole(toDelete, roles.get(i)
							.getRole());
				}

				userManager.delete(toDelete);
				userNames.add(toDelete.getUsername());
			}

			// 保存删除成功的信息
			msg = "deleteSuccess";
			// 日志
			addLog(net.sxnic.comm.log.Log.LOG_OPERATION_DLETE,
					AppContext.getUserName(request)
							+ " delete user sucess! user id:" + id);

		} catch (Exception e) {
			e.printStackTrace();
		}

		return SUCCESS;
	}

}
